#!/usr/bin/env bash

LOG_TAG="[IOS-BUILD]"

log() {
  echo "${LOG_TAG} [$(date '+%Y-%m-%d %H:%M:%S')] $*"
}

buildType="$1"
branch="$2"
clean="$3"
projectPath="$4"
unity="$5"
logFile="${6:-}"

if [[ -z "$buildType" || -z "$branch" || -z "$projectPath" || -z "$unity" ]]; then
  log "Invalid parameter: usage: build_ios_export.sh <DEBUG|RELEASE> <branch> <clean:true|false> <projectPath> <unityPath> [logFile]"
  exit 1
fi

# Normalize build type
buildTypeUpper=$(printf '%s' "$buildType" | tr '[:lower:]' '[:upper:]')
if [[ "$buildTypeUpper" != "DEBUG" && "$buildTypeUpper" != "RELEASE" ]]; then
  log "Invalid parameter: buildType must be DEBUG or RELEASE"
  exit 1
fi
buildType="$buildTypeUpper"

cd "$projectPath" || {
  log "Invalid parameter: projectPath not found: $projectPath"
  exit 1
}

# Update Code
log "Update Code Start"
git checkout "$branch" || exit 1
git fetch origin || exit 1
git pull || exit 1
# git reset --hard "origin/$branch"
log "Update Code Finish"

# Check Changed
log "Check Changed"
buildDir="$projectPath/Build"
curr_buildId="$buildDir/build_id_${buildType}.txt"
last_buildId="$buildDir/build_id_${buildType}_last.txt"
export_dir="$projectPath/Build/IOS/${buildType}"
mkdir -p "$buildDir"

git log -1 --format=%h "origin/$branch" > "$curr_buildId" 2>/dev/null || true

if [[ -f "$last_buildId" && -d "$export_dir" ]]; then
  if cmp -s "$curr_buildId" "$last_buildId"; then
    log "IOS/$buildType exists and up to date; no build needed"
    exit 0
  else
    rm -rf "$export_dir" 2>/dev/null || true
  fi
fi
log "End Check Changed"

cleanLower=$(printf '%s' "$clean" | tr '[:upper:]' '[:lower:]')
if [[ "$cleanLower" == "true" ]]; then
  rm -rf "$projectPath/Assets/StreamingAssets" 2>/dev/null || true
  rm -rf "$projectPath/Build/IOS/${buildType}" 2>/dev/null || true
fi

# PreBuild
log "Prebuild Start"
logSwitch=()
if [[ -n "$logFile" ]]; then
  logSwitch=(-logFile "$logFile")
fi
"$unity" -buildTarget iOS -batchmode -nographics -quit -projectPath "$projectPath" -executeMethod BuildTool.BuildCommand.PreBuild "${logSwitch[@]}"
if [[ $? -ne 0 ]]; then exit 1; fi
log "Prebuild Finish"

# Build iOS (Export Xcode Project)
log "BuildXCODE Start"
rm -rf "$projectPath/Build/IOS/${buildType}" 2>/dev/null || true
"$unity" -batchmode -nographics -quit -projectPath "$projectPath" -executeMethod BuildTool.BuildCommand.BuildIOS "${logSwitch[@]}"
if [[ $? -ne 0 ]]; then exit 1; fi
log "BuildXCODE Finish"

# Mark build id as last
cp -f "$curr_buildId" "$last_buildId" 2>/dev/null || true
log "Export Output (expected dir): $export_dir"
log "BuildIOS Finished"

exit 0

